<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width:75vw">
      <ExamNavBar :examId="examId" :semesterId="semesterId" />
      <div class="exam-container">
        <div style="width: 100px;border-right: 2px dashed red;padding: 20px;background: #fff;text-align: center;font-size: 14px;white-space: nowrap;">
          <div class="exam-left-bar">
            <p class="vertical-text">学校： <span class="underline">{{ studentClass }}</span></p>
            <p class="vertical-text">学号： <span class="underline">{{ major }}</span></p>
            <p class="vertical-text">姓名： <span class="underline">{{ studentName }}</span></p>
          </div>
        </div>
          <div class="exam-content" :data-text="paperTitle">
          <header class="exam-header">
            <h2>{{ paperTitle }}</h2>
            <p>共:【{{ totalMajor }}大题】【{{ totalQuestions }}小题】满分:【{{ totalScore }}分】考试时长:【{{ examDuration }}分钟】</p>
            <p style="font-size:12px; margin:30px 150px">试卷须知：{{ examInstructions }}</p>
            <table class="score-table">
              <thead>
                <tr>
                  <th>题型</th>
                  <th>单选题</th>
                  <th>多选题</th>
                  <th>判断题</th>
                  <th>简答题</th>
                  <th>总分</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>应得分</td>
                  <td>{{ expectedScores.singleChoice }}</td>
                  <td>{{ expectedScores.multipleChoice }}</td>
                  <td>{{ expectedScores.trueFalse }}</td>
                  <td>{{ expectedScores.shortAnswer }}</td>
                  <td>{{ totalScore }}</td>
                </tr>
                <tr>
                  <td>实得分</td>
                  <td>0.0</td>
                  <td>0.0</td>
                  <td>0.0</td>
                  <td>0.0</td>
                  <td>0.0</td>
                </tr>
              </tbody>
            </table>
          </header>
          <section class="exam-questions" v-for="(questionGroup, index) in questionGroups" :key="index">
            <h3 style="padding:10px 0px">{{ index + 1 }}. {{ questionGroup.title }} <span class="blue-text">(共{{ questionGroup.questions.length }}题；共{{ questionGroup.totalScore }}分)</span></h3>
            <div v-for="(question, qIndex) in questionGroup.questions" :key="qIndex" class="question">
              <p><span>{{ qIndex + 1 }}. {{ question.title }} <span class="blue-text">({{ question.score }}分)</span></span></p>
              <ul v-if="question.type === 'only_sel' || question.type === 'yesorno'">
                <li v-for="(option, oIndex) in question.options" :key="oIndex">
                  <input type="radio" :name="'q' + question.id" :checked="option.correct" disabled> {{ String.fromCharCode(65 + oIndex) }}. {{ option.text }}
                </li>
              </ul>
              <ul v-if="question.type === 'many_sel'">
                <li v-for="(option, oIndex) in question.options" :key="oIndex">
                  <input type="checkbox" :name="'q' + question.id" :checked="option.correct" disabled> {{ String.fromCharCode(65 + oIndex) }}. {{ option.text }}
                </li>
              </ul>
              <div v-if="question.type === 'qna'">
                <textarea 
                  rows="4" 
                  style="width:100%;padding-left: 10px;min-height: 150px;" 
                  :value="question.answer"
                  disabled>
                </textarea>
              </div>
            </div>
          </section>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import ExamNavBar from '@/components/ExamNavBar.vue';
import { getPaperHeader, getPaperDetails } from '@/services/api';

export default {
  name: 'PaperPreview',
  components: { ExamNavBar },
  props: {
    examId: [String, Number],
    semesterId: [String, Number]
  },
  setup() {
    const paperId = ref(localStorage.getItem('currentPaperId')); // Retrieve paperId from localStorage
    const paperTitle = ref('');
    const examDuration = ref('');
    const studentClass = ref('');
    const major = ref('');
    const studentName = ref('');
    const examInstructions = ref('');
    const totalMajor = ref(0);
    const totalQuestions = ref(0);
    const totalScore = ref(0);
    const questionGroups = ref([]);
    const expectedScores = ref({
      singleChoice: 0,
      multipleChoice: 0,
      trueFalse: 0,
      shortAnswer: 0
    });

    // Function to strip HTML tags from a string
    const stripHtmlTags = (str) => {
      return str.replace(/<\/?[^>]+(>|$)/g, "");  // Regular expression to remove HTML tags
    };

    // Fetch paper details and header
    const fetchPaperData = async () => {
      try {
        const headerResponse = await getPaperHeader(paperId.value);
        if (headerResponse.status === 200 && headerResponse.data.status === 1) {
          paperTitle.value = stripHtmlTags(headerResponse.data.data.paper_title);  // Remove HTML tags from paper title
          examDuration.value = headerResponse.data.data.during_time;
          examInstructions.value= stripHtmlTags(headerResponse.data.data.paper_content);
        }

        const detailsResponse = await getPaperDetails(paperId.value);
        if (detailsResponse.status === 200 && detailsResponse.data.status === 1) {
          const paperData = detailsResponse.data.data;
          questionGroups.value = paperData.paperList.map(group => ({
            title: stripHtmlTags(group.format_content),  // Remove HTML tags from question group title
            totalScore: group.format_score,
            questions: group.items.map(item => ({
              id: item.qs_id,
              title: stripHtmlTags(item.qs_title),  // Remove HTML tags from question title
              score: item.q_score,
              type: item.qs_type,
              options: item.options ? item.options.map(opt => ({
                text: stripHtmlTags(opt.option_content),  // Remove HTML tags from option text
                correct: opt.is_right
              })) : [],
              answer: stripHtmlTags(item.qna_ans || '')  // Remove HTML tags from answer (if any)
            }))
          }));

          // Calculate total score, expected scores for each type
          totalScore.value = paperData.paperHeader.max_score;
          totalMajor.value = paperData.paperList.length; // Count the number of question types (major questions)
          totalQuestions.value = paperData.paperList.reduce((sum, group) => sum + group.format_qs_cnt, 0); // Count all questions

          // Calculate expected scores for each type
          paperData.paperList.forEach(group => {
            if (group.qs_type === 'only_sel') {
              expectedScores.value.singleChoice += group.format_score;
            } else if (group.qs_type === 'many_sel') {
              expectedScores.value.multipleChoice += group.format_score;
            } else if (group.qs_type === 'yesorno') {
              expectedScores.value.trueFalse += group.format_score;
            } else if (group.qs_type === 'qna') {
              expectedScores.value.shortAnswer += group.format_score;
            }
          });
        }
      } catch (error) {
        console.error('Error fetching paper data:', error);
      }
    };

    onMounted(() => {
      fetchPaperData();
    });

    return {
      paperTitle,
      examDuration,
      studentClass,
      major,
      studentName,
      totalMajor,
      totalQuestions,
      totalScore,
      questionGroups,
      expectedScores,
      examInstructions
    };
  }
};
</script>

<style scoped>
.vertical-text{
  font-size: 16px;
  transform: rotate(-90deg);
  margin: -10px;
}
.underline{
  display: inline-block;
  width: 150px;
  border-bottom: 1px solid black;
  margin-left: 10px;
}
.exam-container {
  display: flex;
  width: 100%;
  background: #F9F9F9;
  justify-content: center;
  padding-bottom: 20px;
}
.exam-left-bar {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-around;
  height: 100vh;
}
.exam-content {
  width: 75vw;
  background: white;
  padding: 20px 40px;
  position: relative;
}
.exam-content::before {
  content: attr(data-text);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-30deg);
  font-size: 60px;
  color: rgba(0, 0, 0, 0.1);
  pointer-events: none;
  white-space: nowrap;
}
.exam-header {
  text-align: center;
  margin-bottom: 20px;
}
.exam-questions {
  border-top: 1px solid #80808047;
  padding-top: 10px;
}
.question {
  margin-bottom: 20px;
  margin-left: 20px;
}
.question ul {
  list-style: none;
  padding-left: 10px;
}
.question li {
  margin: 10px 0;
}
.score-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  font-size: 16px;
  background: #fefefe;
}
.score-table th, .score-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
}
.score-table th {
  background: #f9fbff;
  font-weight: normal;
}
.blue-text {
  font-size: 14px;
  color: gray;
  font-weight: normal;
}
</style>
